#define _CRT_SECURE_NO_WARNINGS
#include "List.h"

LTNode* LTBuyNode(LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(1);
	}

	newnode->data = x;
	newnode->prev = newnode;
	newnode->next = newnode;

	return newnode;
}

LTNode* LTInit()
{
	LTNode* phead = LTBuyNode(-1);
	return phead;
}

LTNode* LTPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);

	/*LTNode* newnode = LTBuyNode(x);
	LTNode* ptail = phead->prev;

	newnode->next = phead;
	newnode->prev = ptail;

	ptail->next = newnode;
	phead->prev = newnode;*/
	LTInsert(phead, x);
}

void LTPrint(LTNode* phead)
{
	assert(phead);

	LTNode* pcur = phead->next;
	printf("guard<==>");
	while (pcur != phead)
	{
		printf("%d<==>", pcur->data);
		pcur = pcur->next;
	}
	printf("\n");
}

void LTPopBack(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);

	/*LTNode* ptail = phead->prev;
	LTNode* prev = ptail->prev;

	prev->next = phead;
	phead->prev = prev;

	free(ptail);
	ptail = NULL;*/
	LTErase(phead->prev);
}

void LTPushFornt(LTNode* phead,LTDataType x )
{
	assert(phead);

	//LTNode* newnode = LTBuyNode(x);
	//LTNode* next = phead->next;

	//newnode->next = next;
	//newnode->prev = phead;

	//next->prev = newnode;
	//phead->next = newnode;
	LTInsert(phead->next,x);
}

bool LTEmpty(LTNode* phead)
{
	return phead->next == phead;
}

void LTPopFornt(LTNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));

	/*LTNode* del = phead->next;
	LTNode* next = del->next;

	next->prev = phead;  
	phead->next = next;

	free(del);
	del = NULL;*/

	LTErase(phead->next);
}

LTNode* LTFind(LTNode* phead,LTDataType x)
{
	assert(phead);

	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);

	LTNode* newnode = LTBuyNode(x);
	LTNode* prev = pos->prev;

	newnode->next = pos;
	newnode->prev = prev;

	prev->next = newnode;
	pos->prev = newnode;
}

void LTErase(LTNode* pos)
{
	assert(pos);

	LTNode* prev = pos->prev;
	LTNode* next = pos->next;

	prev->next = next;
	next->prev = prev;

	free(pos);
	pos = NULL;
}

void LTDestory(LTNode* phead)
{
	assert(phead);

	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		LTNode* next = pcur->next;
		free(pcur);
		pcur = next;
	}

	free(phead);
}